package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.ClientPriceDB;
import com.ramos.kuaixiao.entity.ClientPrice;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.BufferedReader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DownloadClientPriceTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadClientPrice";

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有商品和价格套关联数据
            getAllLocalClientPrice();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void getAllLocalClientPrice() {
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_so_org_customer_salesperson.csv");
        List<ClientPrice> list = readClientPriceCsv(file.getAbsolutePath());
        CommUtil.d(App.mContext, TAG, "tbl_so_org_customer_salesperson:" + list.size());
        ClientPriceDB customerDB = new ClientPriceDB();
        customerDB.addAllClientPrice(list);
    }

    private List<ClientPrice> readClientPriceCsv(String path) {
        List<ClientPrice> readerArr = new ArrayList<>();
        try {
            BufferedReader in = Utils.readCsvBuffer(path);
            in.readLine();
            String stemp = "";
            while ((stemp = in.readLine()) != null) {
                String[] lines = stemp.split(",");
                //Log.d(TAG, "ClientPrice:" + lines[0] + " " + lines[1] + " " + lines[3] + " " + lines[18] );
                ClientPrice bean = new ClientPrice(Utils.replaceStr(lines[0]), Utils.replaceStr(lines[1]), Utils.replaceStr(lines[3]), Utils.replaceStr(lines[18]),Utils.replaceStr(lines[2]));
                readerArr.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllClientPrice() {
        try {
            String url = NetUtils.CLIENT_ALL_PRICE;
            String path = url + SharedPreference.getPreferString("dealer");
            Log.d(TAG, "CLIENT_ALL_PRICE：path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "CLIENT_ALL_PRICE:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            JSONObject data = jsonObejct.getJSONObject("data");
                            List<ClientPrice> customerList = JSONArray.parseArray(data.getJSONArray("data").toString(), ClientPrice.class);
                            if (customerList != null && customerList.size() > 0) {
                                Log.d(TAG, "CLIENT_ALL_PRICE:mCustomerList=" + customerList.size());
                                ClientPriceDB customerDB = new ClientPriceDB();
                                customerDB.addAllClientPrice(customerList);
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
